<?php
/**
 * 接口请求类
 * @author barry
 * 支持毫秒超时、HTTP/HTTPS、代理、debug信息调试
 */
class Curl {

	public static $_timeout = 12000;
	public static $_conect_timeout = 12000;
	public static $_debug = false;
	public static $_request_method = 'GET';
	public static $_user_agent = 'API Center/1.0/ matsumassage';

	/**
	 * curl get请求
	 * @param string $url  请求资源连接
	 *
	 * return string
	 */
	public static function get($url, $header = array(), $curl_opts = null, $proxy = null) {
		self::$_request_method = 'GET';
		$curl = self::_commonStart($url, $header, $curl_opts, $proxy);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, self::$_conect_timeout);
		curl_setopt($curl, CURLOPT_TIMEOUT_MS, self::$_timeout);
		curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
		$result = curl_exec($curl);
		curl_close($curl);
		return $result;
	}

	/**
	 * curl post请求 支持https 伪证书
	 * @param string $url	 	请求资源连接
	 * @param string $param  	请求参数
	 *
	 * return string
	 */
	public static function post($url , $param, $header = array(), $curl_opts = null, $proxy = null) {
		self::$_request_method = 'POST';
		$curl = self::_commonStart($url, $header, $curl_opts, $proxy);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
		curl_setopt($curl, CURLOPT_TIMEOUT_MS, self::$_timeout);
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, self::$_conect_timeout);
		curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
		$result = curl_exec($curl);
		//list($headers, $result) = explode("\r\n\r\n", curl_exec($curl), 2);
		curl_close($curl);
		return $result;
	}

	/**
	 * 公共扩展，支持https、代理
	 * @param string $url
	 * @param string $proxy
	 */
	private static function _commonStart($url, $header, $curl_opts, $proxy = null) {
		$ssl = substr($url, 0, 5);
		$curl = curl_init($url);
		if (!empty($header)) {
			curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		}
		if (($ssl == 'https') || $ssl == 'HTTPS') {
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		}
		if (!empty($proxy)) {
			curl_setopt($curl, CURLOPT_PROXY, $proxy);
			curl_setopt($curl, CURLOPT_HTTPPROXYTUNNEL, 1);
		}
		//curl_setopt($curl, CURLOPT_USERAGENT, self::$_user_agent);
		curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
		curl_setopt($curl, CURLOPT_HEADER, false);

		if (!empty($curl_opts)) {
			foreach ($curl_opts as $key => $value) {
				curl_setopt($curl, $key, $value);
			}
		}
		
		return $curl;
	}
}